package com.block.job.service.channelcost;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.block.common.constant.RedisKeyConstant;
import com.block.common.service.LogFactory;
import com.block.db.entity.ChannelCountInfo;
import com.block.db.mapper.ChannelCountInfoMapper;
import com.block.job.model.KeyInfoDTO;
import lombok.Data;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class ChannelBaiDuCostService {

    private static final Logger log = LogFactory.getJobLog();

    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Autowired
    TransactionTemplate transactionTemplate;
    @Resource
    ChannelCountInfoMapper channelCountInfoMapper;

    private static Map<String, KeyInfoDTO> keyInfoDTOMap = new HashMap<>();
    private static Map<String, String> channelCodeMap = new HashMap<>();



    static {
        keyInfoDTOMap.put("DASOU", new KeyInfoDTO("DASOU", "BDCC-臻享分期大搜的管家", "eyJhbGciOiJIUzM4NCJ9.eyJzdWIiOiJhY2MiLCJhdWQiOiLoh7vkuqvliIbmnJ8iLCJ1aWQiOjU5NDAzNjg3LCJhcHBJZCI6IjRjMjU4NWM4MTEwMmMzYjIzMzY3NDhlZjNmYzcyNjkyIiwiaXNzIjoi5ZWG5Lia5byA5Y-R6ICF5Lit5b-DIiwicGxhdGZvcm1JZCI6IjQ5NjAzNDU5NjU5NTg1NjE3OTQiLCJleHAiOjQxMDI0MTYwMDAsImp0aSI6IjkxNTM3NDA1MTUyMzQ0NjM3NjMifQ.op_VFqN7Z51Co0PaS1T6ZBzjYIXKl7b4FghAZQOSRUxOMxd1hiQzAaMwI_IO01Ke"));

        channelCodeMap.put("臻享分期", "baidu001");
        channelCodeMap.put("来钱呗", "baidu001lqb");
        channelCodeMap.put("可借", "baidu001kejie");
    }

    public void getAccountCost() {

        for (String key : keyInfoDTOMap.keySet()) {
            KeyInfoDTO keyInfoDTO = keyInfoDTOMap.get(key);

            this.getCost(keyInfoDTO);
        }
    }

    public void getCost(KeyInfoDTO keyInfoDTO){

//        String accessToken = this.getToken(keyInfoDTO);
//        String accessToken = "eyJhbGciOiJIUzM4NCJ9.eyJzdWIiOiJhY2MiLCJhdWQiOiLoh7vkuqvliIbmnJ8iLCJ1aWQiOjU5NDAzNjg3LCJhcHBJZCI6IjRjMjU4NWM4MTEwMmMzYjIzMzY3NDhlZjNmYzcyNjkyIiwiaXNzIjoi5ZWG5Lia5byA5Y-R6ICF5Lit5b-DIiwicGxhdGZvcm1JZCI6IjQ5NjAzNDU5NjU5NTg1NjE3OTQiLCJleHAiOjQxMDI0MTYwMDAsImp0aSI6IjkxNTM3NDA1MTUyMzQ0NjM3NjMifQ.op_VFqN7Z51Co0PaS1T6ZBzjYIXKl7b4FghAZQOSRUxOMxd1hiQzAaMwI_IO01Ke";
//        String username = "BDCC-臻享分期大搜的管家";

        Map<String, String> headMap = new HashMap<>();
        headMap.put("userName", keyInfoDTO.getClientId());
        headMap.put("accessToken", keyInfoDTO.getClientSecret());

        Map<String, Object> bizMap = new HashMap<>();
        bizMap.put("reportType", "1743965");
        bizMap.put("timeUnit", "SUMMARY");
        bizMap.put("rowCount", "100");
        bizMap.put("startRow", "0");
        bizMap.put("needSum", true);

        JSONArray jsonArray = new JSONArray();
        jsonArray.add("userName");
        jsonArray.add("realUserId");
        jsonArray.add("impression");
        jsonArray.add("cost");
        jsonArray.add("ctr");
        jsonArray.add("cpc");
        bizMap.put("columns", jsonArray);
        bizMap.put("startDate", LocalDate.now().toString());
        bizMap.put("endDate", LocalDate.now().toString());


        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("header", headMap);
        paramMap.put("body", bizMap);

        /**
         * {"token":"3cfae1b5-2cc3-48fc-b5ae-627039109afd","reportType":"1743965","startDate":"2024-11-26","endDate":"2024-11-26","timeUnit":"SUMMARY","userIds":[],
         * "columns":["userName","realUserId","impression","cost","ctr","cpc"],"sorts":[],"filters":[],"startRow":0,"rowCount":20,"needSum":true,"splitColumn":""}
         */
        String requestUrl = "https://api.baidu.com/json/sms/service/OpenApiReportService/getReportData";

        log.info("header：{}", JSON.toJSONString(headMap));
        log.info("param：{}", JSON.toJSONString(bizMap));

        String response = HttpUtil.createPost(requestUrl)
//                .headerMap(headMap, true)
                .body(JSON.toJSONString(paramMap))
                .execute().body();
        log.info("荣耀成本：{}", response);

        JSONObject resultObject = JSON.parseObject(response);

        Map<String, BigDecimal> channelAmountMap = new HashMap<>();
        channelAmountMap.put("baidu001", BigDecimal.ZERO);
        channelAmountMap.put("baidu001lqb", BigDecimal.ZERO);
        channelAmountMap.put("baidu001kejie", BigDecimal.ZERO);

        JSONObject body = resultObject.getJSONObject("body");
        JSONArray data = body.getJSONArray("data");
        if (ObjectUtil.isNotEmpty(data)){
            JSONObject jsonObject1 = data.getJSONObject(0);
            JSONArray rows = jsonObject1.getJSONArray("rows");
            for (int i = 0; i < rows.size(); i++) {
                JSONObject jsonObject = rows.getJSONObject(i);
                String userName = jsonObject.getString("userName");
                BigDecimal cost = jsonObject.getBigDecimal("cost");

                if (userName.startsWith("臻享分期")){
                    BigDecimal bigDecimal = channelAmountMap.get("baidu001");
                    channelAmountMap.put("baidu001", bigDecimal.add(cost));

                }else if (userName.startsWith("来钱呗")){
                    BigDecimal bigDecimal = channelAmountMap.get("baidu001lqb");
                    channelAmountMap.put("baidu001lqb", bigDecimal.add(cost));

                }else if (userName.startsWith("可借")){
                    BigDecimal bigDecimal = channelAmountMap.get("baidu001kejie");
                    channelAmountMap.put("baidu001kejie", bigDecimal.add(cost));
                }
            }
        }

        transactionTemplate.execute(new TransactionCallback<Object>() {
            @Override
            public Object doInTransaction(TransactionStatus status) {
                String dateInfo = LocalDate.now().toString();
                for (String channelCode : channelAmountMap.keySet()) {
                    BigDecimal bigDecimal = channelAmountMap.get(channelCode);

                    ChannelCountInfo channelCountInfo = channelCountInfoMapper.getEntityByChannelCodeAndDateInfo(channelCode, dateInfo);
                    if (ObjectUtil.isNotEmpty(channelCountInfo)){
                        ChannelCountInfo updateEntity = new ChannelCountInfo();
                        updateEntity.setId(channelCountInfo.getId());
                        updateEntity.setUvCost(bigDecimal);
                        channelCountInfoMapper.updateById(updateEntity);
                    }
                }
                return null;
            }
        });

        return;
    }


//
//    public String getToken(KeyInfoDTO keyInfoDTO) {
//        String redisKey = StrUtil.format(RedisKeyConstant.RONGYAO_CHANNEL_ACCESS_TOKEN, keyInfoDTO.getClientId());
//        String token = stringRedisTemplate.opsForValue().get(redisKey);
//        if (StrUtil.isNotEmpty(token)) {
//            return token;
//        }
//
//        Map<String, Object> bizMap = new HashMap<>();
//        bizMap.put("grant_type", "client_credentials");
//        bizMap.put("client_id", keyInfoDTO.getClientId());
//        bizMap.put("client_secret", keyInfoDTO.getClientSecret());
//
//        String requestUrl = "https://iam.developer.hihonor.com/auth/realms/advertisement/protocol/openid-connect/token";
//
//        String response = HttpUtil.createPost(requestUrl)
//                .form(bizMap)
//                .execute().body();
//
//        JSONObject jsonObject = JSON.parseObject(response);
//        String access_token = jsonObject.getString("access_token");
//
//        if (ObjectUtil.isEmpty(access_token)){
//            throw new RuntimeException("荣耀获取accessToken失败："+response);
//        }
//
//        // 更新access token 缓存信息
//        stringRedisTemplate.opsForValue().set(redisKey, access_token, 50, TimeUnit.MINUTES);
//        return access_token;
//    }

}
